package com.chivan.encoder.log;

import android.text.TextUtils;

import java.util.Iterator;
import java.util.ServiceLoader;

/*
 * Create by weslywang on 2020-01-19
 * Copyright © 2020 Tencent
 *
 * Description:
 */
public class LogcatFactory {
    private boolean showConsoleLog = true;//是否在控制台打印日志（与xlog日志相互独立），开启的情况下可以在没有实现xlog接口的时候打印日志
    private static LogcatFactory mDisplayFactory;
    private ServiceLoader<LogcatInterface> loader;

    private LogcatFactory() {
        loader = ServiceLoader.load(LogcatInterface.class);
    }

    public static LogcatFactory getSingleton() {
        if (null == mDisplayFactory) {
            synchronized (LogcatFactory.class) {
                if (null == mDisplayFactory) {
                    mDisplayFactory = new LogcatFactory();
                }
            }
        }
        return mDisplayFactory;
    }

    enum LogType {
        d,
        i,
        w,
        e
    }

    // 设置控制台日志是否可见
    public void setConsoleLog(boolean enable) {
        showConsoleLog = enable;
    }

    private void log(String tag, String msg, LogType type) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        if (showConsoleLog) {
            System.out.println(String.format("[%s] %s", tag, msg));
        }
        Iterator<LogcatInterface> mIterator = loader.iterator();
//        if (!mIterator.hasNext()) {
//            System.out.println("没有loader");
//            loader = ServiceLoader.load(LogcatInterface.class);
//        }
        while (mIterator.hasNext()) {
            switch (type) {
                case d:
                    mIterator.next().d(tag, msg);
                    break;
                case i:
                    mIterator.next().i(tag, msg);
                    break;
                case w:
                    mIterator.next().w(tag, msg);
                    break;
                case e:
                    mIterator.next().e(tag, msg);
                    break;
            }
        }
    }

    public void d(String tag, String msg) {
        log(tag, msg, LogType.d);
    }

    public void i(String tag, String msg) {
        log(tag, msg, LogType.i);
    }

    public void w(String tag, String msg) {
        log(tag, msg, LogType.w);
    }

    public void e(String tag, String msg) {
        log(tag, msg, LogType.e);
    }
}
